import React, { useEffect, useRef, useCallback } from "react";
import { debounce } from "lodash";
import * as echarts from "echarts/core";
import type { EChartsType } from "echarts/core";
import { PieChart } from "echarts/charts";
import { BarChart, LineChart, RadarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { UniversalTransition } from "echarts/features";
import {
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  VisualMapComponent,
  MarkAreaComponent,
  DataZoomComponent,
} from "echarts/components";
import "./index.less";
import { t } from "i18next";
// import FullScreenBox from '@/components/FullScreenBox';

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  BarChart,
  GridComponent,
  LineChart,
  UniversalTransition,
  RadarChart,
  CanvasRenderer,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  VisualMapComponent,
  MarkAreaComponent,
  DataZoomComponent,
]);

interface IProps {
  chatInfo: {
    msgId: string;
    dataId: string;
  };
  theme: ThemeType;
  chartData: any;
  onRender?: (isForce?: boolean) => void;
}

const ChatEcharts: React.FC<IProps> = ({ chatInfo, chartData, theme }) => {
  // Component State
  const echartsRef = useRef<EChartsType | null>(null);
  const echartsDomRef = useRef<HTMLDivElement>(null);
  const idStr = `chat-echarts-component-${chatInfo.msgId}-${chatInfo.dataId}`;
  // Component Event
  const onResize = useCallback(
    debounce(() => {
      if (echartsRef.current) {
        echartsRef.current.resize();
      }
    }, 100),
    []
  );

  const calculateAxisRange = (
    data: number[],
    defaultRange?: [number, number]
  ) => {
    if (defaultRange) {
      return {
        min: defaultRange[0],
        max: defaultRange[1],
        interval: (defaultRange[1] - defaultRange[0]) / 5,
      };
    }

    if (!data || data.length === 0) {
      return { min: 0, max: 100, interval: 20 };
    }

    const min = Math.min(...data);
    const max = Math.max(...data);

    // 为了美观，稍微扩大范围
    const range = max - min;
    const padding = range * 0.1; // 上下各留10%的空间

    // 计算合适的间隔
    const rawInterval = range / 5; // 希望有5个间隔
    const magnitude = Math.pow(10, Math.floor(Math.log10(rawInterval)));
    let interval = magnitude;

    if (rawInterval / magnitude >= 5) {
      interval = magnitude * 5;
    } else if (rawInterval / magnitude >= 2) {
      interval = magnitude * 2;
    }

    // 调整最小值和最大值，使其为间隔的整数倍
    const adjustedMin = Math.floor((min - padding) / interval) * interval;
    const adjustedMax = Math.ceil((max + padding) / interval) * interval;

    return {
      min: adjustedMin,
      max: adjustedMax,
      interval: interval,
    };
  };

  const generateOption = (data: any) => {
    if (!data) return;

    // 计算X轴范围
    const xRange = {
      min: Math.min(...data.time),
      max: Math.max(...data.time),
    };

    // 获取主题色
    const warningColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-warning-color")
        .trim() || "#f3c452";
    const infoColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-info-color")
        .trim() || "#5ec8f0";
    const successColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-success-color")
        .trim() || "#52c41a";
    const textColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-grey-8")
        .trim() || "#333";
    const borderColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-grey-3")
        .trim() || "#ddd";
    const splitLineColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-grey-2")
        .trim() || "#eee";
    const tooltipBgColor =
      getComputedStyle(document.body)
        .getPropertyValue("--supgpt-grey-7")
        .trim() || "#6a7985";

    const option = {
      color: [warningColor, successColor, infoColor],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: theme === "dark" ? "#333" : tooltipBgColor,
            formatter: function (params: any) {
              if (typeof params.value === "number") {
                return params.value.toFixed(2);
              }
              return params.value;
            },
          },
        },
        formatter: function (params: any) {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((item: any) => {
            result += `${item.marker} ${item.seriesName}: <b>${item.value ? parseFloat(`${item.value}`).toFixed(2) : "--"}</b><br/>`;
          });
          return result;
        },
      },
      legend: {
        data: data.tagNameList || [
          t("pid.chart.pv"),
          t("pid.chart.sv"),
          t("pid.chart.mv"),
        ],
        show: true,
        top: 0,
        left: "center",
        textStyle: {
          color: theme === "dark" ? "#fff" : textColor,
        },
        itemWidth: 15,
        itemHeight: 10,
        icon: "rect",
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "10%",
        top: 80,
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: data.time,
        min: xRange.min,
        max: xRange.max,
        axisLabel: {
          formatter: "{value}",
          color: theme === "dark" ? "#fff" : textColor,
        },
        axisLine: {
          lineStyle: {
            color: theme === "dark" ? "rgba(255, 255, 255, 0.3)" : borderColor,
          },
        },
      },
      yAxis: [
        {
          type: "value",
          name: "PV/SP",
          position: "left",
          min: "dataMin",
          max: "dataMax",
          axisLine: {
            show: true,
            lineStyle: {
              color: warningColor,
            },
          },
          axisLabel: {
            formatter: function (value: number) {
              return value.toFixed(2);
            },
            color: theme === "dark" ? "#fff" : textColor,
          },
          nameTextStyle: {
            color: theme === "dark" ? "#fff" : textColor,
          },
          splitLine: {
            lineStyle: {
              color:
                theme === "dark" ? "rgba(255, 255, 255, 0.1)" : splitLineColor,
              type: "dashed",
            },
          },
        },
        {
          type: "value",
          name: t("pid.chart.controlOutput"),
          position: "right",
          min: "dataMin",
          max: "dataMax",
          axisLine: {
            show: true,
            lineStyle: {
              color: infoColor,
            },
          },
          axisLabel: {
            formatter: function (value: number) {
              return value.toFixed(2);
            },
            color: theme === "dark" ? "#fff" : textColor,
          },
          nameTextStyle: {
            color: theme === "dark" ? "#fff" : textColor,
          },
          splitLine: {
            show: false,
          },
        },
      ],
      dataZoom: [
        {
          type: "inside",
          start: 0,
          end: 100,
          zoomOnMouseWheel: true,
          moveOnMouseMove: true,
          xAxisIndex: [0],
          filterMode: "filter",
        },
      ],
      series: [
        {
          name: data.tagNameList ? data.tagNameList[0] : t("pid.chart.pv"),
          type: "line",
          yAxisIndex: 0,
          data: data.pv,
          smooth: true,
          lineStyle: {
            width: 2,
            color: warningColor,
          },
          symbol: "none",
          connectNulls: true,
          sampling: "average",
        },
        {
          name: data.tagNameList ? data.tagNameList[1] : t("pid.chart.sv"),
          type: "line",
          yAxisIndex: 1,
          data: data.sp,
          smooth: false,
          lineStyle: {
            width: 2,
            color: successColor,
            type: "dashed",
          },
          symbol: "none",
          connectNulls: true,
          sampling: "average",
        },
        {
          name: data.tagNameList ? data.tagNameList[2] : t("pid.chart.mv"),
          type: "line",
          yAxisIndex: 0,
          data: data.mv,
          smooth: true,
          lineStyle: {
            width: 2,
            color: infoColor,
          },
          symbol: "none",
          connectNulls: true,
          sampling: "average",
        },
      ],
    };
    return option;
  };

  const processNewFormatData = (data: any) => {
    if (!data) return null;
    console.log(data);
    // 提取时间点（假设数据是按时间顺序排列的）
    const timePoints = Array.from(
      { length: data.data.length / data.tagNameList.length },
      (_, i) => i
    );

    // 初始化各曲线数据
    const pvData: number[] = [];
    const spData: number[] = [];
    const mvData: number[] = [];

    for (let i = 0; i < data.data.length; i++) {
      const [tagName, value] = data.data[i];
      if (tagName === data.tagNameList[0]) {
        // PV
        pvData.push(value);
      } else if (tagName === data.tagNameList[1]) {
        // SP
        spData.push(value);
      } else if (tagName === data.tagNameList[2]) {
        // MV
        mvData.push(value);
      }
    }

    return {
      time: timePoints,
      pv: pvData,
      sp: spData,
      mv: mvData,
      pvSvRange: data.pvSvRange,
      mvRange: data.mvRange,
      tagNameList: data.tagNameList,
    };
  };
  const getOptions = (data: any) => {
    let options: any = {};
    const processedData = processNewFormatData(data);
    if (processedData) {
      options = generateOption(processedData);
    }
    return options;
  };
  // Component Effect
  useEffect(() => {
    if (
      echartsDomRef.current &&
      chartData &&
      Object.keys(chartData).length > 0
    ) {
      if (echartsRef.current) echartsRef.current = null;
      const options = getOptions(chartData);
      echartsRef.current = echarts.init(echartsDomRef.current, theme);
      echartsRef.current.setOption(options);
    }
  }, [chartData]);

  useEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
      for (let entry of entries) {
        onResize();
      }
    });

    if (echartsDomRef.current) {
      resizeObserver.observe(echartsDomRef.current);
    }

    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  return (
    <div
    // resize={onResize}
    >
      <div
        id={idStr}
        className="pid-data-trend-echarts"
        ref={echartsDomRef}
      ></div>
    </div>
  );
};

export default ChatEcharts;
